package Muilticast;



import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;

import Twitter.RequestSender.RequestSender;

import twitter.RequestParser.ServerRegistrateNoticeParser;
import twitter.TwitterLibrary.SocketConfig;
import twitter.TwitterLibrary.Utility;

public class MulticastReceiver implements Runnable {
	
	private ServerRegistrateNoticeParser parser;
	private RequestSender sender;
	
	public MulticastReceiver(Utility utility)
	{

		this.parser=new ServerRegistrateNoticeParser(utility);
		this.sender=new RequestSender(utility);
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true)
		{
			// Which port should we listen to
			int port = 9991;
			// Which address
			String group = "230.0.0.1";

			

			// Create the socket and bind it to port 'port'.
			MulticastSocket s;
			
			try {
				s = new MulticastSocket(port);
				s.joinGroup(InetAddress.getByName(group));

				// join the multicast group
				
				// Now the socket is set up and we are ready to receive packets

				

				// Create a DatagramPacket and do a receive\
				byte buf[]=new byte[1024];
				
				DatagramPacket pack = new DatagramPacket(buf, buf.length);
				s.receive(pack);

				
				String data=new String(pack.getData(),0,pack.getLength());

				StringTokenizer st=new StringTokenizer(data);
				String ss=st.nextToken();
				//System.out.println("token:"+ss);
				//System.out.println("config.randomNumber"+config.randomNumber);
				int random=Integer.parseInt(ss);
				
				if (random!=SocketConfig.identifier)
				{
					// Finally, let us do something useful with the data we just received,
					// like print it on stdout :-)
					
					System.out.write(pack.getData(),0,pack.getLength());
				

					String result=parser.readQuery(data);

					sender.sendRequest(SocketConfig.primaryIp, result+"\r\n notification \r\n", SocketConfig.backendPort);
					
					//System.out.println();

					// And when we have finished receiving data leave the multicast group and
					// close the socket
					s.leaveGroup(InetAddress.getByName(group));
					s.close();
				}
				
				
			
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}

}
